package com.anasit.motor.wxapi;

import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.json.JSONArray;
import org.json.JSONException;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * Created by BeanYon on 2017/1/3.
 */
public class WechatPlugin extends CordovaPlugin {
  /**
   * 微信App Id
   */
  public static String APP_ID = "";
  /**
   * 微信商户号
   */
  public static String PARTNER_ID = "";
  private static final String ACTION_FLAG_LOGIN = "login";
  private static final String ACTION_FLAG_SHARE = "share";
  private static final String ACTION_FLAG_PAY = "pay";
  private IWXAPI api;
  private static Context mContext = null;
  public static CallbackContext mCallBackContext;

  @Override
  public boolean execute(String action, final JSONArray args, final CallbackContext callbackContext) throws JSONException {
    mCallBackContext = callbackContext;
    mContext = cordova.getActivity();
    List<String> ids = readMetaDataFromApplication();
    APP_ID = ids.get(0);
    PARTNER_ID = ids.get(1);
    api = WXAPIFactory.createWXAPI(mContext, APP_ID);
    api.registerApp(APP_ID);

    readMetaDataFromApplication();

    if (api.isWXAppInstalled()) {
      if (ACTION_FLAG_LOGIN.equals(action)) {
        login();//微信登录
      } else if (ACTION_FLAG_SHARE.equals(action)) {
        share(args.getString(2), args.getString(3), args.getString(4), args.getBoolean(5));//微信分享
      } else if (ACTION_FLAG_PAY.equals(action)) {
        pay(args.getString(2), args.getString(3), args.getString(4), args.getString(5));//微信支付
      }
    } else {
      WechatPlugin.mCallBackContext.success("no wechat");
    }

    return true;
  }

  /**
   * 读取application 节点  meta-data 信息
   *
   * @return 微信APP_ID、PARTNERID
   */
  private List<String> readMetaDataFromApplication() {
    try {
      ApplicationInfo appInfo = mContext.getPackageManager()
              .getApplicationInfo(mContext.getPackageName(),
                      PackageManager.GET_META_DATA);
      List<String> ids = new ArrayList<String>();
      ids.add(appInfo.metaData.getString("ANAS_WECHAT_ID"));
      ids.add(appInfo.metaData.getString("ANAS_WECHAT_PARTNERID"));
      return ids;
    } catch (PackageManager.NameNotFoundException e) {
      e.printStackTrace();
    }
    return null;
  }

  /**
   * 微信登录
   */
  private void login() {
    String uuid = UUID.randomUUID().toString();
    final SendAuth.Req req = new SendAuth.Req();
    req.scope = "snsapi_userinfo";
    req.state = uuid;
    boolean b = api.sendReq(req);
  }

  /**
   * 微信分享
   *
   * @param url        分享链接
   * @param title      分享标题
   * @param des        分享描述
   * @param isTimeline 是否分享到朋友圈
   */
  private void share(String url, String title, String des, boolean isTimeline) {
    WXWebpageObject webpage = new WXWebpageObject();
    webpage.webpageUrl = url;
    WXMediaMessage msg = new WXMediaMessage(webpage);
    msg.title = title;
    msg.description = des;
    int smallIconId = mContext.getResources().getIdentifier("share_icon", "mipmap", mContext.getPackageName()) == 0 ? mContext.getResources().getIdentifier("share_icon", "drawable", mContext.getPackageName()) : mContext.getResources().getIdentifier("share_icon", "mipmap", mContext.getPackageName());
    Bitmap thumb = BitmapFactory.decodeResource(mContext.getResources(), smallIconId);
    msg.thumbData = bmpToByteArray(thumb, true);

    SendMessageToWX.Req req = new SendMessageToWX.Req();
    req.transaction = buildTransaction("webpage");
    req.message = msg;
    req.scene = isTimeline ? SendMessageToWX.Req.WXSceneTimeline : SendMessageToWX.Req.WXSceneSession;
    api.sendReq(req);
  }

  /**
   * 微信支付
   *
   * @param prepayid 预支付订单id
   * @param sign     包含支付信息的签名
   */
  private void pay(String prepayid, String sign, String nonceStr, String timeStamp) {
    PayReq req = new PayReq();
    req.appId = APP_ID;
    req.partnerId = PARTNER_ID;
    req.prepayId = prepayid;
    req.nonceStr = nonceStr;
    req.timeStamp = timeStamp;
    req.packageValue = "Sign=WXPay";
    req.sign = sign;

    Log.i("BeanYon:", "appid = " + req.appId);
    Log.i("BeanYon:", "partnerId = " + req.partnerId);
    Log.i("BeanYon:", "prepayId = " + prepayid);
    Log.i("BeanYon:", "nonceStr = " + nonceStr);
    Log.i("BeanYon:", "timeStamp = " + timeStamp);
    Log.i("BeanYon:", "packageValue = " + req.packageValue);
    Log.i("BeanYon:", "sign = " + sign);
//    req.extData = "摩托购付款"; // optional
    api.sendReq(req);
  }

  private byte[] bmpToByteArray(final Bitmap bmp, final boolean needRecycle) {
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    bmp.compress(Bitmap.CompressFormat.PNG, 40, output);
    if (needRecycle) {
      bmp.recycle();
    }

    byte[] result = output.toByteArray();
    try {
      output.close();
    } catch (Exception e) {
      e.printStackTrace();
    }

    return result;
  }

  private String buildTransaction(final String type) {
    return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();
  }
}
